package util

import (
	"reflect"
	"strings"
)

func ContainsString(formats []string, format string) bool {
	for _, f := range formats {
		if f == format {
			return true
		}
	}
	return false
}

// GetMimeType 根据格式获取对应的MIME类型
func GetMimeType(format string) string {
	switch format {
	case "excel":
		return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	case "csv":
		return "text/csv; charset=utf-8"
	case "pdf":
		return "application/pdf"
	default:
		return "application/octet-stream"
	}
}

func CleanAllNullChars(data interface{}) {
	if data == nil {
		return
	}

	val := reflect.ValueOf(data)

	// 解引用指针/接口
	for val.Kind() == reflect.Ptr || val.Kind() == reflect.Interface {
		if val.IsNil() {
			return
		}
		val = val.Elem()
	}

	switch val.Kind() {
	case reflect.String:
		// 清理字符串中的 \x00
		str := val.String()
		cleaned := strings.ReplaceAll(str, "\x00", "")
		if val.CanSet() {
			val.SetString(cleaned)
		}

	case reflect.Map:
		// 遍历 map，清理键和值
		for _, key := range val.MapKeys() {
			// 清理键（如果是字符串）
			if key.Kind() == reflect.String {
				keyStr := key.String()
				cleanedKey := strings.ReplaceAll(keyStr, "\x00", "")
				if cleanedKey != keyStr && val.CanSet() {
					// 替换 map 键（先删后加）
					val.SetMapIndex(key, reflect.Value{})
					newKey := reflect.ValueOf(cleanedKey)
					val.SetMapIndex(newKey, val.MapIndex(key))
					key = newKey
				}
			}
			// 递归清理值
			CleanAllNullChars(val.MapIndex(key).Interface())
		}

	case reflect.Slice, reflect.Array:
		// 遍历切片/数组，清理每个元素
		for i := 0; i < val.Len(); i++ {
			elem := val.Index(i)
			if elem.CanInterface() {
				CleanAllNullChars(elem.Interface())
			}
		}

	case reflect.Struct:
		// 处理结构体字段（如 Student、Grade 等自定义类型）
		for i := 0; i < val.NumField(); i++ {
			field := val.Field(i)
			if field.CanInterface() {
				CleanAllNullChars(field.Interface())
			}
		}
	}
}
